/*
 * @Author: TJN tjn@246@126.com
 * @Date: 2024-06-25 09:45:51
 * @LastEditors: TJN tjn@246@126.com
 * @LastEditTime: 2024-06-25 15:58:14
 * @FilePath: \hdcms-nest\src\validate\validatePassword.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { BadRequestException } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { verify } from 'argon2';
import {
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
} from 'class-validator';

export function validatePassword(
  property: string,
  validationOptions?: ValidationOptions,
) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'validatePassword',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        async validate(value: any, args: ValidationArguments) {
          const prisma = new PrismaClient();
          const user = await prisma.user.findFirst({
            where: {
              name: args.object['name'], // 假设您的对象中包含用户名
            },
          });

          if (!user.password) {
            console.log(111);

            throw new BadRequestException();
          }
          console.log(user.password);

          return Boolean(await verify(user.password, value));
        },
      },
    });
  };
}
